/**
 * 用户相关接口
 */
import request from './index'

// 用户登录
export function login(data) {
  return request({
    url: '/user/login',
    method: 'post',
    data
  })
}

// 用户注册
export function register(data) {
  return request({
    url: '/user/register',
    method: 'post',
    data
  })
}

// 获取用户信息
export function getUserInfo(userId) {
  return request({
    url: `/user/${userId}`,
    method: 'get'
  })
}

// 获取当前用户信息
export function getCurrentUser() {
  return request({
    url: '/user/current',
    method: 'get'
  })
}

// 修改个人资料
export function updateUserProfile(data) {
  return request({
    url: '/user/profile',
    method: 'put',
    data
  })
}

// 修改密码
export function changePassword(data) {
  return request({
    url: '/user/password',
    method: 'put',
    data
  })
}

// 上传用户头像
export function uploadAvatar(data) {
  return new Promise((resolve, reject) => {
    // 获取token
    const token = localStorage.getItem('token')
    
    // 创建URL
    let url = '/api/upload/avatar'
    
    // 如果有token，通过URL参数传递
    if (token) {
      const urlObj = new URL(url, window.location.origin)
      urlObj.searchParams.append('token', token)
      url = urlObj.pathname + urlObj.search
    }
    
    const xhr = new XMLHttpRequest()
    xhr.open('POST', url, true)
    xhr.withCredentials = true
    
    // 只设置安全的header
    xhr.setRequestHeader('Accept', 'application/json')
    
    xhr.onload = function() {
      if (xhr.status === 200) {
        try {
          const response = JSON.parse(xhr.responseText)
          // 确保返回标准响应格式
          if (!response.code && response.code !== 0) {
            response.code = 0
          }
          resolve(response)
        } catch (e) {
          console.error('解析响应失败:', e, xhr.responseText)
          reject(new Error('解析响应失败'))
        }
      } else {
        reject(new Error(`上传失败: ${xhr.status}`))
      }
    }
    
    xhr.onerror = function() {
      reject(new Error('网络错误，上传失败'))
    }
    
    xhr.send(data)
  })
}

// 获取用户发布的文章
export function getUserArticles(userId, params) {
  return request({
    url: `/user/${userId}/articles`,
    method: 'get',
    params
  })
}

// 获取用户收藏的文章
export function getUserFavorites(params) {
  return request({
    url: '/user/favorites',
    method: 'get',
    params
  })
}

// 关注用户
export function followUser(userId) {
  return request({
    url: `/user/follow/${userId}`,
    method: 'post'
  })
}

// 取消关注用户
export function unfollowUser(userId) {
  return request({
    url: `/user/follow/${userId}`,
    method: 'delete'
  })
}

// 获取关注列表
export function getFollowing(userId, params) {
  return request({
    url: `/user/${userId}/following`,
    method: 'get',
    params
  })
}

// 获取粉丝列表
export function getFollowers(userId, params) {
  return request({
    url: `/user/${userId}/followers`,
    method: 'get',
    params
  })
}

// 获取未读消息数量
export function getUnreadMessageCount() {
  return request({
    url: '/message/unread/count',
    method: 'get'
  })
}

// 获取用户消息
export function getUserMessages(params) {
  return request({
    url: '/message',
    method: 'get',
    params
  })
}

// 标记消息为已读
export function markMessageRead(messageId) {
  return request({
    url: `/message/read/${messageId}`,
    method: 'put'
  })
}

// 标记全部消息为已读
export function markAllMessagesRead() {
  return request({
    url: '/message/read/all',
    method: 'put'
  })
}

// 删除消息
export function deleteMessage(messageId) {
  return request({
    url: `/message/${messageId}`,
    method: 'delete'
  })
} 